import router from '@/router'
import aside from './aside'

export default {
  state: {
    tabsListState: [
      {
        id: 0,
        name: '/welcome',
        title: '首页',
        path: '/welcome',
        affix: true
      }
    ],
    tabfocusState: 0
  },
  mutations: {
    addTabMutations(state, target) {
      // console.log(target, 'fff')
      const tabs = state.tabsListState
      for (let index = 0; index < tabs.length; index++) {
        const element = tabs[index]
        if (element.name === target.path) {
          state.tabfocusState = target.path
          return
        }
      }
      state.tabsListState.push({
        title: target.auth_name,
        name: target.path,
        id: target.id,
        pid: target.pid
      })
      state.tabfocusState = target.path
    },
    removeTabMutations(state, targetName) {
      const tabs = state.tabsListState
      let activeName = state.tabfocusState
      console.log(activeName + ',' + targetName)
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
              // this.findTab(nextTab)
              nextTab.$attrs = nextTab
              console.log(nextTab)
              this.commit('opentabMutations', nextTab)
              // router.push({ name: nextTab.path })
            }
          }
        })
      }
      state.tabfocusState = activeName
      state.tabsListState = tabs.filter(tab => tab.name !== targetName)
    },
    opentabMutations(state, target) {
      state.tabfocusState = target.name
      const path = target.name.split('/').slice(-1)
      console.log(path)
      router.push({ name: path })
    },
    tabfoucus(state, value) {
      state.tabfocusState = value
    }
  },
  actions: {
    // 生成tabs列表
    initTabsList({ commit }) {
      if (aside.state.clickMenuPath === '/welcome') { // 首页
        commit('tabfoucus', '/welcome')
      }

      const target = aside.state.menuRulesState.filter(item => item.path === aside.state.clickMenuPath)[0]
      if (target === undefined) return
      commit('addTabMutations', target)
    }
  }
}
